package com.zhuo.schoolproject.service.Impl;

import cn.dev33.satoken.error.SaErrorCode;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuo.schoolproject.entitys.LoginUser;
import com.zhuo.schoolproject.entitys.User;
import com.zhuo.schoolproject.entitys.properties.SatokenProperties;
import com.zhuo.schoolproject.mapper.UserMapper;
import com.zhuo.schoolproject.service.UserService;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;


@Service
@Transactional
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {
    private final UserMapper userMapper;
    private final SatokenProperties satokenProperties;

    //登录接口
    @Override
    public SaResult login(LoginUser user) {
        //查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 == null) return SaResult.error("没有此用户");
        if (user1.getStatus() != 0)
            return SaResult.error("账户处于异常状态");
        String s = SaSecureUtil.aesEncrypt(satokenProperties.getVerifykey(),user1.getPassword());
        if(s.equals(user.getPassword())){
            StpUtil.login(user1.getPhone());
            return SaResult.data(StpUtil.getTokenInfo());
        }
        return SaResult.error("密码错误");
    }

    @Override
    public SaResult selectUser(Long id){
        User user = userMapper.selectById(id);
        if (user==null) return SaResult.error("查询不出此用户");
        user.setPassword(null);
        return SaResult.data(user);
    }

    @Override
    public SaResult updateUser(User user) {
        //1.根据id去查询，
        User user1 = userMapper.selectById(user.getId());
        if (user1 == null) return SaResult.error("查无此用户");
        //2.看有没有传递密码
        if (user.getPassword() != null && !"".equals(user.getPassword().trim())) {
            String s = SaSecureUtil.aesEncrypt(satokenProperties.getVerifykey(), user.getPassword());
            user.setPassword(s);
        }
        //3.调用mapper执行sql
        return userMapper.updateById(user) > 0 ? SaResult.ok("修改成功") : SaResult.error("修改失败");
    }

    @Override
    public SaResult saveUser(User user){
        //1.先查电话号码
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,user.getPhone());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1!=null) return SaResult.error("此电话号码已经被注册了");
        //2.密码加密
        String s = SaSecureUtil.aesEncrypt(satokenProperties.getVerifykey(),user.getPassword());
        user.setPassword(s);
        //3.保存数据

        return userMapper.insert(user)>0?SaResult.ok("添加成功"):SaResult.error("添加失败");
    }

    @Override
    public SaResult deleteUser(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            return SaResult.error("用户ID不能为空或无效");
        }

        // 2. 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            return SaResult.error("用户不存在");
        }

        // 3. 执行删除操作
        int result = userMapper.deleteById(id);

        // 4. 返回结果
        if (result > 0) {
            return SaResult.ok("删除成功");
        } else {
            return SaResult.error("删除失败");
        }
    }

    @Override
    public SaResult selectPage(Integer current, Integer size, Map<String,Object>search){
        Page<User> page = new Page<>(current,size);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (search.get("startTime")!=null&&!"".equals(search.get("startTime"))){
            queryWrapper.ge(User::getSubmitTime,search.get("startTime"));
        }
        if (search.get("endTime")!=null&&!"".equals(search.get("endTime"))){
            queryWrapper.le(User::getSubmitTime,search.get("endTime"));
        }
        Page<User>page1 = userMapper.selectPage(page, queryWrapper);
         for (User record : page1.getRecords()){
             //密码制空
             record.setPassword(null);
             //冗余字段填充
             if (record.getStatus()==0){
                 record.setStatusName("生效");
             }else{
                 record.setStatusName("失效");
             }

         }
        return SaResult.data(page1);
    }

    /**
     * 退出接口     发现一个问题，就是请求这个接口必须要携带token，如果没有携带token会导致redis中的数据还存在
     *
     * @return
     */
    @GetMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("退出成功");
    }


}
